#!/bin/sh

HOSTCONF=/etc/hostconfig
TOOLS_DIR=/Library/Parallels/Tools/

#  The logging routine
Log() {
	logger -p install.info -t 'Parallels Installer' "$@"
}

CheckProcessRunning()
{
	Log "Calling CheckProcessRunning"
	process=`ps -w -w -A -ocommand 2>/dev/null | grep "${1}" | grep -v 'grep'`
	if [ $? -eq 0 ]; then
		Log "Process found: ${process}"
		return 0
	fi

	return 1
}

# Wait till dispatcher started.
WaitDispatcherStart() {
	# Wait for Dispatcher to start
	COUNTER=21
	while [ $COUNTER -gt 1 ]; do
		if CheckProcessRunning "prl_disp_service"; then
			Log "Dispatcher is up and running"
			break
		fi
		sleep 1
		let COUNTER-=1	
	done
}

# Convert ISO to tarball
# $1 - path to ISO
# $2 - path to converted tarball
Iso2Tgz () {
    local iso_path=$1
    local tarball_path=$2
    local status=0

    # Create temporary mountpoint
    mount_point=`mktemp -d /tmp/iso2tgz.XXXXXX`
    if [ ! -d "$mount_point" ]; then
      Log "Iso2Tgz: cannot create temporary mountpoint ${mount_point}"
      return 1
    fi

    # Suspend 'CrossOver CD Helper' in order no to show
    # automaunt message box (bug #124850)
    killall -SIGSTOP 'CrossOver CD Helper'

    # Mount ISO to temporary mountpoint
    if hdiutil attach -nobrowse -mountpoint "${mount_point}" "${iso_path}"; then
        # Pack content of ISO
        if tar c -C "${mount_point}" ./ | gzip -1 > "${tarball_path}"; then
            # Unmount temporary mount point
            if ! hdiutil detach "${mount_point}"; then
		    Log "Iso2Tgz: cannot unmount ${mount_point}" && \
		    status=$(expr ${status} + 1)
            fi
        else
            Log "Iso2Tgz: cannot pack content of ${mount_point} to ${tarball_path}"
            status=$(expr ${status} + 1)
        fi
    else
        Log "Iso2Tgz: cannot mount ${iso_path} to ${mount_point}"
        status=$(expr ${status} + 1)
    fi

    # Reenable 'CrossOver CD Helper'
    killall -SIGCONT 'CrossOver CD Helper'

    # Remove temporary mount point
    rm -rf "${mount_point}"

    return ${status}
}

Log 'running postinstall script' # DEBUG

export PATH=$PATH:/usr/bin

python_bins="
python2.5
python2.6
python
"

for python_bin in $python_bins; do
    if type $python_bin > /dev/null 2>&1; then
        # Path to Python's 'site-package' directory
        PythonSitePackageDir=$($python_bin -c "from distutils.sysconfig import get_python_lib; print get_python_lib()")

        Log "PythonSitePackageDir = ${PythonSitePackageDir}"

        # Create link to Python module
        if [ -n "${PythonSitePackageDir}" ]; then
            ln -sf $(echo ${PythonSitePackageDir} | sed 's,/[^/]*,../,g')"Library/Parallels/Parallels Service.app/Contents/Frameworks/ParallelsVirtualizationSDK.framework/Libraries/Python/prlsdkapi" "${PythonSitePackageDir}/prlsdkapi"
        fi
    fi
done

#  Dispatcher only packages
if $(echo "${1}" | grep -vqs '\<Console\>' >/dev/null); then
	Log 'This is Server so we enabling service' # DEBUG

	#  Register Parallels dispatcher service
	grep -qs '^[[:space:]]*PARALLELS=' "${HOSTCONF}" || 
	 echo 'PARALLELS=-YES-' >> "${HOSTCONF}"

	# Retouch server bundles in order to flush cache
	Log "Retouch server bundles" # DEBUG
	touch '/Library/Parallels/Parallels Service.app' \
	      '/Library/Parallels/Parallels Service.app/Contents/MacOS/Parallels Updater.app'


	#  Reset kernel extensions cache
	touch '/Library/Parallels/Parallels Service.app/Contents/Kexts'
	
	#  This is a workaround for tmp dir issue
	#  Unset environ TMPDIR
	TMPDIR_env="${TMPDIR}"
	unset TMPDIR

	#  Run Parallels dispatcher
	Log 'Starting service' # DEBUG

	# To get rid of unwanted message about
	# "New Unconfigured Adapters Have Appeared",
	# block UserNotification center until dispatcher is started.
    darwin_version="$(uname -r | awk 'BEGIN { FS = "." } ; { print $1 }')"
		
	if test ${darwin_version:-9} -gt 8; then
		launchctl unload /System/Library/LaunchDaemons/com.apple.UserNotificationCenter.plist
	fi

	if [ -e /Library/LaunchDaemons/com.parallels.server.launchdaemon.plist ]; then
		launchctl load /Library/LaunchDaemons/com.parallels.server.launchdaemon.plist
		launchctl start com.parallels.server.launchdaemon
	fi
	if [ -e /Library/LaunchDaemons/com.parallels.desktop.launchdaemon.plist ]; then
		launchctl load /Library/LaunchDaemons/com.parallels.desktop.launchdaemon.plist
		launchctl start com.parallels.desktop.launchdaemon
	fi
	if [ -e /Library/LaunchDaemons/com.parallels.stm.launchdaemon.plist ]; then
		launchctl load /Library/LaunchDaemons/com.parallels.stm.launchdaemon.plist
		launchctl start com.parallels.stm.launchdaemon
	fi

	#  Restore environ TMPDIR
	TMPDIR="${TMPDIR_env}"
	export TMPDIR

	WaitDispatcherStart

	# Load UserNotificationCenter launchd back again.
	if test ${darwin_version:-9} -gt 8; then
		launchctl load /System/Library/LaunchDaemons/com.apple.UserNotificationCenter.plist
	fi

else
	# Retouch client bundles in order to flush cache
	Log "Retouch client bundles" # DEBUG
	touch '/Applications/Parallels Management Console.app'
fi

if $(echo "${1}" | grep -qs '\<Desktop\>' >/dev/null); then
	# Retouch desktop bundles in order to flush cache
	Log "Retouch desktop bundles" # DEBUG
	touch '/Applications/Parallels Desktop.app'

	if [ -d '/Applications/Parallels Desktop.app/Contents/MacOS/PD_Starter.app' ]; then
		touch '/Applications/Parallels Desktop.app/Contents/MacOS/PD_Starter.app'
	fi
fi

# Convert ISOs to tarballs
Log 'Converting ISO to tarball'
for iso in prl-tools-win.iso prl-tools-lin.iso; do
	if [ ! -e "${TOOLS_DIR}/${iso}" ]; then
		Log "File ${TOOLS_DIR}/${iso} is missing"
		continue
	fi

	Log "Converting ${iso} to ${iso%%.iso}.tar.gz"
	if ! Iso2Tgz "${TOOLS_DIR}/${iso}" "${TOOLS_DIR}/${iso%%.iso}.tar.gz"; then
		Log "Failed to convert ${iso} to ${iso%%.iso}.tar.gz"
	fi
done

if [ -e "/Library/StartupItems/ParallelsDispatcherService/ParallelsDispatcherService" ]; then
	/Library/StartupItems/ParallelsDispatcherService/ParallelsDispatcherService ext-load
fi
if [ -e "/Library/Parallels/Parallels Service.app/Contents/Resources/ParallelsDispatcherService" ]; then
	Log "Fixing dock icon for user $i"
	"/Library/Parallels/Parallels Service.app/Contents/Resources/ParallelsDispatcherService" ext-load
fi

if [ -d "${1}/../../../../Learn your Mac.app" ]; then
	cp -RH "${1}/../../../../Learn your Mac.app" "/Applications/Learn your Mac.app"
elif [ -d "/Volumes/Parallels Desktop 4 Switch to Mac/Learn your Mac.app" ]; then
	cp -RH "/Volumes/Parallels Desktop 4 Switch to Mac/Learn your Mac.app" "/Applications/Learn your Mac.app"
elif [ -d "/Volumes/Parallels Desktop 5 Switch to Mac/Learn your Mac.app" ]; then
	cp -RH "/Volumes/Parallels Desktop 5 Switch to Mac/Learn your Mac.app" "/Applications/Learn your Mac.app"
fi

# Copy Parallels Transporter Agent for Windows
if [ -e "${1}/../../../../.Parallels Transporter Agent for Windows.exe" ]; then
	cp "${1}/../../../../.Parallels Transporter Agent for Windows.exe" "/Library/Parallels/Parallels Transporter Agent for Windows.exe"
	chmod 664 "/Library/Parallels/Parallels Transporter Agent for Windows.exe"
elif [ -e "/Volumes/Parallels Desktop 4 Switch to Mac/.Parallels Transporter Agent for Windows.exe" ]; then
	cp "/Volumes/Parallels Desktop 4 Switch to Mac/.Parallels Transporter Agent for Windows.exe" "/Library/Parallels/Parallels Transporter Agent for Windows.exe"
	chmod 664 "/Library/Parallels/Parallels Transporter Agent for Windows.exe"
elif [ -e "/Volumes/Parallels Desktop 5 Switch to Mac/.Parallels Transporter Agent for Windows.exe" ]; then
	cp "/Volumes/Parallels Desktop 5 Switch to Mac/.Parallels Transporter Agent for Windows.exe" "/Library/Parallels/Parallels Transporter Agent for Windows.exe"
	chmod 664 "/Library/Parallels/Parallels Transporter Agent for Windows.exe"
fi

# Remove old downloaded PIS package if there are any
PIS='/Library/Parallels/Downloads/pis.msi'
[ -f "$PIS" ] && rm -f "$PIS"

pd25="Parallels.app"
pd3="Parallels\ Desktop.app"
pd4="\/Applications\/Parallels\ Desktop.app\/"
# Change dock icon path
for i in `ls -1 /Users/ | grep -ivw Shared | grep -ve '^\\.'`; do
	# if PD4 icon is not presented in dock
	sudo -u $i defaults read com.apple.dock persistent-apps 2>/dev/null | grep -qs "$pd4"
	if [ $? -ne 0 ]; then
		#if PD3 icon presented in dock
		sudo -u $i defaults read com.apple.dock persistent-apps 2>/dev/null | grep -qs "$pd25"
		ret=$?
		sudo -u $i defaults read com.apple.dock persistent-apps 2>/dev/null | grep -qs "$pd3"
		if [ $ret -eq 0 -o $? -eq 0 ]; then
			Log "Fixing dock icon for user $i"
			counter=0
			app_list=$(sudo -u $i defaults read com.apple.dock persistent-apps | grep "_CFURLString\"" | sed 's/.*"_CFURLString" = "//' | sed 's/";.*//')
			IFS=$'\n'
			for app in $app_list; do
        			app=$(echo $app | sed "s/\/.*${pd25}.*/$pd4/" | sed "s/\/.*${pd3}.*/$pd4/")
        			opt="-array-add"
        			if [ $counter -eq 0 ]; then
					opt="-array"
        			fi
        			sudo -u $i defaults write com.apple.dock persistent-apps $opt "<dict><key>tile-data</key><dict><key>file-data</key><dict><key>_CFURLString</key><string>$app</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>"
        			counter=1
			done
			unset IFS

			sudo -u $i killall Dock
		fi
	fi
done

SWD=`cd "${0%/*}"; pwd`
. "${SWD}"/receipt.sh

# Warm up client app
ParallelsClient="/Applications/Parallels Desktop.app/Contents/MacOS/PD_Starter.app/Contents/MacOS/prl_client_app"
if [ -e "${ParallelsClient}" ]; then
	Log "Worming up client application"
	sudo -u $USER "${ParallelsClient}" --mode cache_install
fi

# Get product version
ver=$(python -c "import plistlib; print plistlib.readPlist(\"${0%/*}/../Info.plist\")[\"CFBundleShortVersionString\"]")
# Skip revision; the version should be in format  X.X.XXXXXX
ver=${ver%.*}

# Get product name without spaces
dist_file="${0%/*}/../../../../distribution.dist"
prod=$(grep '<title>' "$dist_file" | sed s/.*\<title\>//g | sed s/\<.*\>//g | sed s/\ //g)

if [ -z "$prod" -o -z "$ver" ]; then
	Log "Can not determinate product name or version"
else
	stats_dir="/var/db/Parallels/Stats"
	mkdir -p "$stats_dir"
	# Create the installation receipt to CEP tool
	date "+%Y-%m-%d %H:%M:%S %z" > "$stats_dir/$prod.$ver"
fi

# Wait for it!
wait
#Just to finish installation
# with good mood
true
